/**
 * Magic ComboBox AutoComplete Plugin v1.0
 * author: Mac_J@boarsoft.com
 * need combo.js, core.js
 */
mac.combo_autoCp = function(self, cfg) {
	cfg = $.extend(self.config, {
		autoCp : $.extend({}, cfg)
	});
	var acfg = cfg.autoCp;
	var sc = 'selected', hc = 'hover'
	var tf = self.children('.head').find('input');
	var bd = self.children('.body');
	var fb = acfg.by || cfg.keyField;
	tf.keyup(function(e) {
		var k = e.keyCode, op = self.isOpen;
		var rs = bd.children('.tr'), v = ':visible';
		switch (k) {
		case 38: // UP
		case 40: // DOWN
			var x, d = (k == 40);
			if (!op && d)
				self.open();
			rs = rs.filter(v);
			var h = rs.filter('.' + hc), s = rs.filter('.' + sc);
			rs.removeClass(hc);
			var hx = (d ? h.nextAll(v) : h.prevAll(v)).first();
			var sx = (d ? s.nextAll(v) : s.prevAll(v)).first();
			if (h.length + s.length == 0 || hx.length + sx.length == 0) {
				x = (d ? rs.first() : rs.last());
			} else if (hx.length) {
				x = hx;
			} else if (sx.length && op && !h.length) {
				x = sx;
			} else if (s.length && !op) {
				x = s;
			} else {
				x = x = (d ? rs.first() : rs.last());
			}
			x.addClass(hc);
			return false;
		case 13:// RETURN
			if (op)
				bd.children('.' + hc).mousedown();
			break;
		case 27:// ESC
			self.close();
			break;
		default:
			var v = tf.val(), lt = bd.children('.tr');
			if (!v || v.length < (acfg.minChars || 4)) {
				lt.show();
				break;
			}
			if (v != self.displayValue) {
				var dd = self.data;
				lt.each(function(n, c) {
					var ec = $(c), k = ec.attr('name')
						, b, x = dd[k][fb] + '';
					if (cfg.equals) {
						b = cfg.equals(x, k, v, dd);
					} else {
						b = x && x.indexOf(v) > -1;
					}
					ec.toggle(b);
				});
				if (!self.isOpen)
					self.open();
			}
		}
		return true;
	}).keydown(function(e) {
		switch (e.keyCode) {
		case 9: // TAB
			var v = tf.val();
			if (v && v != self.displayValue){
				var lt = bd.children('.tr:visible'), k;
				if (lt.length == 1) {
					k = lt.first().attr('name');
					v = self.data[k][fb];
				}
				
//				if (acfg.strict) {
					self.select(k);
//				} else {
//					if (k) {
//						self.select(k);
//					} else {
//						self.selected = [v];
//					}
//					self.close();
//				}
				return 1;
			}
			break;
		}
		return 1;
	});
	return self;
}